package com.engr.lyx.blog.biz.interceptor;

import com.engr.lyx.common.annotation.FreeAccess;
import com.engr.lyx.common.consts.AuthConsts;
import com.engr.lyx.common.security.UserHelper;
import com.engr.lyx.common.utils.ResponseMapUtils;
import com.engr.lyx.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author sa
 */
@Component
@Slf4j
public class ApiRequestInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		// 获取token
		String authToken = request.getHeader(AuthConsts.TOKEN_HEADER);
		log.info("{}", authToken);
		if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			FreeAccess freeAccess = handlerMethod.getBean().getClass().getAnnotation(FreeAccess.class);
			FreeAccess freeAccessMethod = handlerMethod.getMethodAnnotation(FreeAccess.class);
			if (freeAccess != null || freeAccessMethod != null) {
				return true;
			} else if (StringUtils.isNoneBlank(authToken)) {
				UserDetails userDetails = UserHelper.getUserAuth();
				if (userDetails != null) {
					UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
							userDetails, "N/A", userDetails.getAuthorities());
					authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
					return true;
				}
				ResponseMapUtils.responseMapMessage(request,response,HttpServletResponse.SC_UNAUTHORIZED,"token 已失效或未登录");
				return false;
			} else {
				ResponseMapUtils.responseMapMessage(request,response,HttpServletResponse.SC_UNAUTHORIZED,"token 已失效或未登录");
				return false;
			}
		}
		return super.preHandle(request, response, handler);
	}
}
